package com.aweqy.hrmanager.controller;

import com.aweqy.hrmanager.entity.User;
import com.aweqy.hrmanager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/users")
public class UserController {
    @Autowired
    private UserService userService;
    
    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @GetMapping
    public List<User> list() {
        return userService.list();
    }

    @PostMapping
    public boolean add(@RequestBody User user) {
        // 加密密码
        if (user.getPasswordHash() != null && !user.getPasswordHash().startsWith("$2a$")) {
            user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
        }
        // 设置创建时间
        user.setCreatedAt(new Date());
        user.setUpdatedAt(new Date());
        return userService.save(user);
    }

    @PutMapping
    public boolean update(@RequestBody User user) {
        // 如果密码不为空且不是已加密的格式，则加密
        if (user.getPasswordHash() != null && !user.getPasswordHash().startsWith("$2a$")) {
            user.setPasswordHash(passwordEncoder.encode(user.getPasswordHash()));
        }
        // 设置更新时间
        user.setUpdatedAt(new Date());
        return userService.updateById(user);
    }

    @DeleteMapping("/{id}")
    public boolean delete(@PathVariable Integer id) {
        return userService.removeById(id);
    }
} 